import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import JobDetail from '@/views/JobDetail.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import UserCenter from '@/views/UserCenter.vue'
import AdminPanel from '@/views/AdminPanel.vue'
import CustomerForm from '@/views/CustomerForm.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/job/:id',
    name: 'JobDetail',
    component: JobDetail
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/user',
    name: 'UserCenter',
    component: UserCenter,
    meta: { requiresAuth: true }
  },
  {
    path: '/admin',
    name: 'AdminPanel',
    component: AdminPanel,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  {
    path: '/form/:jobId',
    name: 'CustomerForm',
    component: CustomerForm
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const userRole = localStorage.getItem('userRole')
  
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if (to.meta.requiresAdmin && userRole !== 'admin') {
    next('/')
  } else {
    next()
  }
})

export default router 